<!--端口检测-->
<template>
  <div class="h-[100%] box-border w-[100%]">
    <el-card shadow="always">
      <el-form
        size="default"
        inline="true"
        label-width="auto"
        class="translate-y-2"
      >
        <el-form-item label="设备SN号:">
          <el-input
            style="width: 240px"
            placeholder="请输入设备SN号"
            v-model="dataParams.sn"
            clearable
          />
        </el-form-item>
        <el-form-item label="设备连接端口:">
          <el-input
            style="width: 240px"
            placeholder="请输入设备连接端口"
            v-model="dataParams.srcPort"
            clearable
          />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input
            style="width: 240px"
            placeholder="例:kk"
            v-model="dataParams.remark"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button :icon="Download" type="primary" @click="downloadAddTemp"
            >批量添加模板下载</el-button
          >
          <el-button
            :icon="Upload"
            type="primary"
            @click="
              () => {
                batchAddDialog = true;
                batchAdd = {
                  file: null,
                  remark: '',
                };
                if (uploadForm) {
                  uploadForm.clearFiles();
                }
              }
            "
            >批量添加</el-button
          >
          <el-button
            :icon="Refresh"
            type="primary"
            @click="getDataForwardDataList"
            >搜索</el-button
          >
          <el-button
            :icon="Sunny"
            type="primary"
            @click="openForwardDialog(true)"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
   
    <div class="flex h-[90%] mt-2">
      <el-card class="cardData" style="width: 100%; height: 100%">
        <el-table
          height="65vh"
          :border="true"
          :data="dataList"
          v-loading="tableLoading"
          :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="id" label="编号" width="80"></el-table-column>
          <el-table-column prop="sn" label="SN" width="150"></el-table-column>
          <el-table-column label="服务名" width="120">
            <template #default="scope">
              <span>{{
                forwardDataList.find(
                  (item) => item.id == scope.row.parseServerUrlId
                )?.parseName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="stationId"
            label="站点ID"
            width="80"
          ></el-table-column>
          <el-table-column prop="srcPort" label="入站端口" />
          <el-table-column
            prop="tranTcpUrl"
            label="TCPURL"
            width="120"
          ></el-table-column>
          <el-table-column prop="srcConnectSize" label="入站连接数量">
            <template #default="scope">
              <el-tag
                effect="light"
                style="width: 3vw"
                :type="scope.row.srcConnectSize == 0 ? 'danger' : 'success'"
              >
                {{ scope.row.srcConnectSize }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="forwardDataSize" label="转发数据量(KB)" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column
            prop="updatedAt"
            label="最新数据转发时间"
            :formatter="
              (row) => dayjs(row.updatedAt).format('YYYY-MM-DD HH:mm:ss')
            "
          />
          <el-table-column prop="status" label="启用状态">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#B9B9B9"
                :active-value="true"
                :inactive-value="false"
                :loading="switchLoading"
                @change="startCloseDataForward(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-button
                :icon="EditPen"
                :disabled="scope.row.status"
                @click="openForwardDialog(false, scope.row)"
                >修改
              </el-button>

              <el-button
                :icon="Delete"
                type="danger"
                @click="deleteDataForward(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex w-[100%] justify-end mt-2">
          <el-pagination
            v-model:current-page="dataParams.pageNum"
            v-model:page-size="dataParams.pageSize"
            :page-sizes="[10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="dataTotal"
            @size-change="
              (number) => {
                getDataForwardDataList();
              }
            "
            @current-change="
              (number) => {
                getDataForwardDataList();
              }
            "
          />
        </div>
      </el-card>
    </div>
  </div>
  <el-dialog
    draggable
    v-model="addOrUpdateDataForwardDialog"
    :title="title"
    width="500"
  >
    <el-form inline label-width="100" ref="addForm">
      <el-form-item label="SN:" prop="sn">
        <el-input v-model="addForward.sn" placeholder="请输入设备SN"></el-input>
      </el-form-item>
      <el-form-item label="PORT:" prop="srcPort">
        <el-input
          v-model.number="addForward.srcPort"
          placeholder="请输入RTCM端口端口"
        ></el-input>
      </el-form-item>
      <el-form-item label="StationId:" prop="stationId">
        <el-input
          v-model.number="addForward.stationId"
          placeholder="请输入站点ID"
        ></el-input>
      </el-form-item>

      <el-form-item label="备注:" prop="remark">
        <el-input
          v-model="addForward.remark"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>

      <el-form-item label="TCP转发:" prop="tranTcpUrl">
        <el-input
          v-model="addForward.tranTcpUrl"
          placeholder="请输入TCP转发地址"
        ></el-input>
      </el-form-item>

      <el-form-item label="解算服务" prop="parseServerUrlId">
        <el-select
          v-model="addForward.parseServerUrlId"
          placeholder="请选择"
          style="width: 150px"
        >
          <el-option
            v-for="item in forwardDataList"
            :label="item.parseName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :icon="CloseBold" @click="addDataForwardDialog = false"
          >关闭</el-button
        >
        <el-button :icon="Check" type="primary" @click="addForwardDataFunction">
          提交</el-button
        >
      </div>
    </template>
  </el-dialog>
  <!--    批量添加dialog-->
  <el-dialog draggable v-model="batchAddDialog" width="1000">
    <el-form inline>
      <el-form-item label="备注：">
        <el-input
          v-model="batchAdd.remark"
          placeholder="请输入备注信息"
        ></el-input>
      </el-form-item>
      <el-form-item label="模板：" label-width="150px">
        <el-upload
          :limit="1"
          ref="uploadForm"
          :auto-upload="false"
          action="#"
          @change="
            (e) => {
              batchAdd.file = e.raw;
            }
          "
        >
          <template #trigger>
            <el-button style="width: 10vw" type="primary"
              >点击模板上传</el-button
            >
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchAddDialog = false">取消</el-button>
        <el-button type="primary" @click="batchAddDataForwardFunction">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

import { ElMessage, ElLoading } from "element-plus";
import {
  Delete,
  Refresh,
  Sunny,
  CloseBold,
  Check,
  Download,
  Upload,
  EditPen,
} from "@element-plus/icons-vue";
import type { ComponentSize } from "element-plus";
import {
  AddDataForwardApi,
  DeleteDataForwardApi,
  SelectDataForwardListApi,
  DownloadAddTempApi,
  StartCloseDataForwardApi,
  BatchAddDataForwardApi,
  UpdateDataForwardApi,
} from "../../service/port";
import type { SearchDataForwardParams } from "../../service/port";
import type { DataForwardAddParams } from "../../service/port";
import type { StartCloseDataParams } from "../../service/port";
import dayjs from "dayjs";
import { da, fa } from "element-plus/es/locales.mjs";
import { getDataForwardParsesAPI } from "@/api/solutionService";
import type { DataForwardParseServer } from "@/model/solutionService";

/**
 * 公共数据
 */
const addOrUpdateDataForwardDialog = ref(false);
const tableLoading = ref(false);
const addForm = ref();
const batchAddDialog = ref(false);

/**
 * 弹窗打开函数 flag : true 添加, false 修改
 */
const openForwardDialog = (flag: boolean, data?: any) => {
  console.log("打开弹窗", flag, data);
  if (flag) {
    title.value = "添加转发记录";
    addForward.value = {
      srcPort: undefined,
      remark: "",
      sn: "",
      stationId: undefined,
    };
  } else {
    title.value = "修改转发记录";
    addForward.value = data;
  }
  addOrUpdateDataForwardDialog.value = true;
};

/**
 * 转发数据获取*************************
 */
//数据列表
const dataList = ref([]);
const dataTotal = ref(0);
//数据查询参数
const dataParams = ref<SearchDataForwardParams>({
  pageSize: 10,
  pageNum: 1,
  remark: "",
  sn: "",
  srcPort: undefined,
});
const getDataForwardDataList = async () => {
  tableLoading.value = true;
  const res = await SelectDataForwardListApi(dataParams.value);
  if (res.data.list == null) {
    dataList.value = [];
  } else {
    dataList.value = res.data.list.map((v) => {
      v.forwardDataSize = v.forwardDataSize.toFixed(1);
      return v;
    });
  }
  dataTotal.value = res.data.total;
  tableLoading.value = false;
};
/**
 * 智翔转发数据记录添加
 */

const addForward = ref<DataForwardAddParams>({
  srcPort: undefined,
  remark: "",
  sn: "",
  stationId: undefined,
  tranTcpUrl: undefined,
});

const title = ref("");

const addForwardDataFunction = async () => {
  let res = null;
  if (title.value == "添加转发记录") {
    res = await AddDataForwardApi(addForward.value);
  } else {
    res = await UpdateDataForwardApi(addForward.value);
  }

  if (res.code == 200) {
    ElMessage.success(title.value == "添加转发记录" ? "新增成功" : "修改成功");
  } else {
    ElMessage.error(res.data);
  }

  addOrUpdateDataForwardDialog.value = false;
  getDataForwardDataList();
};

/**
 * 转发记录删除
 */
const deleteDataForward = async (row) => {
  if (row.status) {
    ElMessage.warning("启用状态禁止删除");
    return;
  }
  const res = await DeleteDataForwardApi(row.id);
  if (res.code == 200) {
    ElMessage.success("删除成功");
  } else {
    ElMessage.error(res.data);
  }
  getDataForwardDataList();
};

/**
 * 批量模板下载
 */
const downloadAddTemp = async () => {
  const res = await DownloadAddTempApi();
  const link = document.createElement("a");
  try {
    let blob = new Blob([res], { type: "application/vnd.ms-excel" });

    link.style.display = "none";
    // 兼容不同浏览器的URL对象
    const url = window.URL || window.webkitURL || window.moxURL;

    link.href = url.createObjectURL(blob);
    link.setAttribute("download", "example.xlsx");

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    url.revokeObjectURL(link.href); //销毁url对象
    ElMessage.warning("文件下载中");
  } catch (e) {
    console.log("下载的文件出错", e);
  }
};

/**
 * 批量添加
 */
const batchAdd = ref<{ remark: string; file: any }>({
  remark: "",
  file: null,
});
const uploadForm = ref();

const batchAddDataForwardFunction = async () => {
  if (batchAdd.value.file == null || batchAdd.value.remark == "") {
    ElMessage.warning("请完善提交参数");
    return;
  }
  const data = new FormData();
  data.append("file", batchAdd.value.file);
  data.append("remark", batchAdd.value.remark);
  const res = await BatchAddDataForwardApi(data);
  if (res.code == 200) {
    ElMessage.success("批量添加成功");
  } else {
    ElMessage.error(res.data);
  }
  batchAddDialog.value = false;
  getDataForwardDataList();
};

/**
 * 开启或者关闭智翔转发服务
 */
const switchLoading = ref(false);
const startCloseDataForward = async (row) => {
  switchLoading.value = true;
  const params: StartCloseDataParams = {};
  params.srcPort = row.srcPort;
  params.flag = row.status;
  const res = await StartCloseDataForwardApi(params);
  if (res.code == 200) {
    ElMessage.success("执行成功");
  } else {
    ElMessage.error(res.data);
  }
  switchLoading.value = false;

  getDataForwardDataList();
};

/**
 *
 * 解算服务
 * 列表
 */

const forwardDataList = ref<DataForwardParseServer[]>([]);

/**
 * 获取解算服务列表
 */
async function getForwardDataList() {
  const {
    data: { list, total },
  } = await getDataForwardParsesAPI({
    pageNum: 1,
    pageSize: 1000,
  });
  forwardDataList.value = list ?? [];
}

/**
 *  周期钩子函数********************************
 */

onMounted(() => {
  getDataForwardDataList();
  getForwardDataList();
  console.log("智翔转发页面加载", this);
});
</script>

<style scoped>
.container {
  box-sizing: border-box;
  height: 100%;
}

::v-deep(.el-table .success) {
  background-color: #e9ffdb;
}

::v-deep(.el-table .fail) {
  background-color: #ffc87c;
}

[type="file"] {
  color: red;
  /* font-size: 0; */
}

/* 主按钮的样式自定义 */
::file-selector-button {
  height: 2.5rem;
  color: #fff;
  border-radius: 0.25rem;
  border: 1px solid #2a80eb;
  padding: 0.75rem 1rem;
  background-color: #2a80eb;
  cursor: pointer;
}

::-ms-browse {
  height: 3rem;
  color: #fff;
  border-radius: 0.25rem;
  border: 1px solid #2a80eb;
  padding: 0.75rem 1rem;
  background-color: #2a80eb;
  cursor: pointer;
}

.page {
  position: absolute;
  bottom: 10px;
  left: 400px;
}

/*
.cardData {
  position: relative;
  height: 95%;
} */

.card {
  /* width: 80vw; */
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.card2 {
  height: 80px;
  width: 200px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.isActive {
  background-color: red;
  color: bisque;
}

.header {
  /* background-color: rgb(240, 240, 240); */
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 10%;
}

.main {
  display: flex;
  height: 90%;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
